import { observable } from "mobx";
import http from 'libs/http';
import { message, Modal } from 'antd';
import moment from 'moment';
import * as XLSX from 'xlsx';

class Store {
  @observable records = [];
  @observable record = {};
  @observable detail_record = {};
  @observable isFetching = false;
  @observable formVisible = false;
  @observable detailVisible = false;
  @observable assignVisible = false;
  @observable orderAssignVisible = false;
  @observable shops = [];
  @observable city = [];
  @observable sku = [];
  @observable selectedRowKeys = []; // 选中的行keys
  @observable selectedRows = []; // 选中的行数据

  @observable f_order_no = '';
  @observable f_order_status = '';
  @observable f_order_mobile = '';
  @observable f_mobile = '';

  // 过滤条件
  @observable filters = {
    order_no: '',
    student_name: '',
    parent_name: '',
    parent_phone: '',
    student_type: '',
    class_type: '',
    grade: '',
    status: '',
    payment_type: '',
    date_range: [],
    school_name: '',
  };

  // 订阅回调函数列表
  subscribers = [];

  // 添加订阅
  subscribe = (callback) => {
    this.subscribers.push(callback);
    // 返回取消订阅的函数
    return () => {
      this.subscribers = this.subscribers.filter(cb => cb !== callback);
    };
  };

  // 通知所有订阅者
  notifySubscribers = () => {
    this.subscribers.forEach(callback => callback());
  };

  // 设置过滤条件
  setFilters = (values) => {
    this.filters = { ...this.filters, ...values };
    this.notifySubscribers();
  };

  // 重置过滤条件
  resetFilters = () => {
    this.filters = {
      order_no: '',
      student_name: '',
      parent_name: '',
      parent_phone: '',
      student_type: '',
      class_type: '',
      grade: '',
      status: '',
      payment_type: '',
      date_range: [],
      school_name: '',
    };
    this.notifySubscribers();
  };

  // 获取订单列表
  fetchRecords = () => {
    this.isFetching = true;
    
    // 构建查询参数
    const params = {};
    Object.keys(this.filters).forEach(key => {
      if (this.filters[key]) {
        if (key === 'date_range' && this.filters[key].length === 2) {
          params.start_date = moment(this.filters[key][0]).format('YYYY-MM-DD');
          params.end_date = moment(this.filters[key][1]).format('YYYY-MM-DD');
        } else {
          params[key] = this.filters[key];
        }
      }
    });
    
    console.log('请求参数:', params);
    
    http.get('/api/order/order/', { params })
      .then(res => {
        console.log('获取订单响应:', res);
        this.records = res;
        // 清空选择
        this.updateSelection([], []);
      })
      .catch(error => {
        console.error('获取订单列表失败:', error);
        message.error('获取订单列表失败');
      })
      .finally(() => this.isFetching = false);
  };

  // 导出数据到Excel
  exportToExcel = (exportType) => {
    let dataToExport = [];
    
    switch (exportType) {
      case 'selected':
        // 选择导出
        if (!this.selectedRowKeys || this.selectedRowKeys.length === 0) {
          message.warning('请至少选择一条记录');
          return;
        }
        console.log('导出选中的行:', this.selectedRowKeys.length, '条数据');
        dataToExport = this.selectedRows;
        break;
      case 'all':
        // 全部导出
        dataToExport = this.records;
        break;
      default:
        dataToExport = this.records;
    }
    
    if (dataToExport.length === 0) {
      message.warning('没有可导出的数据');
      return;
    }
    
    try {
      // 定义字段映射和表头
      const fieldMapping = {
        order_no: '订单编号',
        student_name: '学生姓名',
        parent_name: '家长姓名',
        parent_phone: '家长手机',
        student_type: '学员类型',
        class_type: '上课类型',
        grade: '年级',
        class_number: '班级',
        school_name: '学校名称',
        exam_year: '考试年份',
        total_amount: '订单金额(元)',
        payment_type: '支付方式',
        payment_code: '付款码',
        status: '订单状态',
        created_at: '创建时间',
        paid_time: '支付时间'
      };
      
      // 格式化数据
      const formattedData = dataToExport.map(item => {
        const formattedItem = {};
        
        // 遍历映射，格式化每个字段
        Object.keys(fieldMapping).forEach(key => {
          let value = item[key];
          
          // 特殊字段处理
          if (key === 'class_type') {
            value = value === 'in_school' ? '校内上课' : '校外上课';
          } else if (key === 'grade') {
            const gradeMap = {
              'grade_1': '高一',
              'grade_2': '高二',
              'grade_3': '高三'
            };
            value = gradeMap[value] || value;
          } else if (key === 'class_number' && value) {
            value = value.replace('class_', '') + '班';
          } else if (key === 'payment_type') {
            value = value === 'wechat' ? '微信支付' : '线下汇款';
          } else if (key === 'status') {
            const statusMap = {
              'pending': '待支付',
              'paid': '已支付',
              'cancelled': '已取消'
            };
            value = statusMap[value] || value;
          }
          
          formattedItem[fieldMapping[key]] = value !== undefined && value !== null ? value : '';
        });
        
        return formattedItem;
      });
      
      // 创建工作簿和工作表
      const ws = XLSX.utils.json_to_sheet(formattedData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '订单数据');
      
      // 导出文件
      const fileName = `订单数据_${moment().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
      XLSX.writeFile(wb, fileName);
      
      message.success(`成功导出${formattedData.length}条记录`);
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error('导出失败: ' + error.message);
    }
  };

  // 显示订单详情
  showDetail = (info) => {
    this.detailVisible = true;
    this.detail_record = info;
    
    // 获取订单详情
    http.get(`/api/order/order/${info.id}/`)
      .then(res => {
        this.detail_record = res;
      })
      .catch(error => {
        console.error('获取订单详情失败:', error);
        message.error('获取订单详情失败');
      });
  };

  // 关闭订单详情
  closeDetail = () => {
    this.detailVisible = false;
    this.detail_record = {};
  };

  // 显示表单
  showForm = (info = {}) => {
    this.formVisible = true;
    this.record = info;
  };

  // 关闭表单
  closeForm = () => {
    this.formVisible = false;
    this.record = {};
  };

  // 取消订单
  cancelOrder = (orderId) => {
    Modal.confirm({
      title: '确认取消订单',
      content: '确定要取消该订单吗？取消后不可恢复。',
      onOk: () => {
        http.post(`/api/order/order/${orderId}/cancel/`)
          .then(() => {
            message.success('订单已取消');
            this.fetchRecords();
          })
          .catch(error => {
            console.error('取消订单失败:', error);
            message.error('取消订单失败');
          });
      }
    });
  };

  // 确认线下支付
  confirmPayment = (orderId) => {
    Modal.confirm({
      title: '确认支付',
      content: '确认该订单已完成线下支付？',
      onOk: () => {
        http.post(`/api/order/order/${orderId}/confirm_payment/`)
          .then(() => {
            message.success('订单支付已确认');
            this.fetchRecords();
          })
          .catch(error => {
            console.error('确认支付失败:', error);
            message.error('确认支付失败');
          });
      }
    });
  };

  // Helper method to update selections
  updateSelection = (selectedRowKeys, selectedRows) => {
    this.selectedRowKeys = selectedRowKeys || [];
    this.selectedRows = selectedRows || [];
    // Log the updated selection for debugging
    console.log('Store selection updated:', this.selectedRowKeys.length, 'items');
  }
}

export default new Store()
